package com.simplerobot.core;



import org.apache.log4j.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Service代理
 * Created by Administrator on 2017/3/10.
 */
public class ServiceProxy implements InvocationHandler {
    public static Logger log = Logger.getLogger(ServiceProxy.class);
    /*Service对象*/
    private BaseService service;

    public ServiceProxy(BaseService service){
        this.service = service;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log.info("动态代理执行前");
        Object result = null;
        byte state = 0;
        try {
            result = method.invoke(this.service, args);
        } catch (IllegalAccessException e) {
            log.error(e);
            state = -1;
        } catch (IllegalArgumentException e) {
            log.error(e);
            state = -1;
        } catch (InvocationTargetException e) {
            log.error(e);
            state = -1;
        }
        switch (state){
            case 0:
                service.sessionCommit();
                break;
            case -1:
                service.sessionRollback();
                break;
        }
        log.info("动态代理执行后");
        return result;
    }

    public static void main(String[] args) {

    }
}
